package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"libraryAutoGrab/common/response"
	"libraryAutoGrab/db/redis"
	"libraryAutoGrab/model/dto/input"
	"libraryAutoGrab/service"
	"libraryAutoGrab/service/impl"
	"time"
)

var libraryService service.LibraryService = impl.NewLibraryServiceImpl()
var redisClient = redis.NewRedis()



/**
	抢座函数
	功能:监听空闲座位然后抢座(开选择不开启抢座)，然后发送邮箱提醒
 */
func GrabHandler(ctx *gin.Context) {
	area := ctx.Query("area"); autoGrab := ctx.Query("autoGrab") == "true"; body, _ := ioutil.ReadAll(ctx.Request.Body)
	var userinfo input.UserInfo
	json.Unmarshal(body, &userinfo)
	var list []map[string]string
	var token,segment string
	if autoGrab {
		token = libraryService.Login(userinfo.UserId, userinfo.Password)
		if token == "" {
			response.Fail(ctx, "学号或密码错误", nil)
			return
		}
		segment = libraryService.GetSpareTime(area)
	}
	ticker := time.NewTicker(time.Second * 2)
	redisClient.Set(ctx,"listen:"+userinfo.Email,1,time.Minute*30) //最多持续监听半小时，半小时后自动停止监听
	go func() {
		for range ticker.C {
			v, _ := redisClient.Get(ctx, "listen:"+userinfo.Email).Int()
			if v == 0  {
				break	//若监听的状态不为1则表示被停止或时间到，则取消监听
			}
			println("正在寻找")
			list = libraryService.GetSpareSeat(area)
			if len(list) != 0 {
				if autoGrab {
					println("我开始自动抢座了")
					seatId := list[0]["id"]
					hasGrab := libraryService.BookSeat(token, userinfo.UserId, seatId, segment)
					if hasGrab {
						libraryService.AnnounceEmail(userinfo.Email, list, autoGrab);
						redisClient.Del(ctx,"listen:"+userinfo.Email)
						break
					}
				} else {
					println("找到座位了")
					libraryService.AnnounceEmail(userinfo.Email, list, autoGrab)
					redisClient.Del(ctx,"listen:"+userinfo.Email)
					break
				}
			}
		}
		return
	}()
	response.Success(ctx, "已经成功开启监听", list)
}

/**
	停止抢座函数
	功能:停止抢座
 */
func StopHandler(ctx *gin.Context) {
	body, _ := ioutil.ReadAll(ctx.Request.Body)
	var userinfo input.UserInfo
	json.Unmarshal(body, &userinfo)
	v, _ := redisClient.Get(ctx, "listen:"+userinfo.Email).Int()
	if v == 0 {
		response.Success(ctx,"已经停止，此次停止监听无效", nil)
		return
	}
	redisClient.Del(ctx, "listen:"+userinfo.Email)
	response.Success(ctx, "成功停止监听", nil)
	return
}


